package cn.boyu.interceptor;

import cn.boyu.entity.SysUser;
import cn.boyu.result.AjaxResult;
import cn.boyu.service.ISysUserService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/*拦截器 判断是否登录或登录过期*/
@Component
public class CheckLoginInterceptor implements HandlerInterceptor {

    @Autowired
    private ISysUserService sysUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//如果请求为 OPTIONS 请求，则返回 true,否则需要通过jwt验证
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())){
            System.out.println("OPTIONS请求，放行");
            return true;
        }
//        HandlerMethod method = (HandlerMethod) handler;


//        response.setHeader("Access-Control-Allow-Origin", request.getHeader("origin"));
//        //该字段可选，是个布尔值，表示是否可以携带cookie
//        response.setHeader("Access-Control-Allow-Credentials", "true");
//        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT,OPTIONS");
//        response.setHeader("Access-Control-Allow-Headers", "*");
//        if (request.getMethod().equals(HttpMethod.OPTIONS.name())){
//            response.setStatus(HttpStatus.NO_CONTENT.value());
//        }

//        response.setHeader("Access-Control-Allow-Origin", request.getHeader("token"));

//        System.err.println(request.getHeader("Referer"));

        String token = request.getHeader("token");
        System.err.println("token: "+ token);
        SysUser user = sysUserService.getUserByToken(token);
//        System.err.println(" token: "+token+" method: "+method+" request: "+request);
        if (user == null) {
            AjaxResult err = AjaxResult.error("未登录！请重新登录");
            response.setContentType("application/json;charset=utf-8");
            Map<String,Object> map = new HashMap<>();
            map.put("code",233);
            map.put("msg","未登录！请重新登录");
            response.getWriter().write(JSON.toJSONString(err));
            return false;
        }
        return true;
    }
}




















